#include "stdafx.h"
#include "net/FTPStreamFactory.hpp"
#include "net/FTPClientSession.hpp"
#include "net/URIStreamOpener.hpp"
#include "stream/streambuf.hpp"
using JHCPP::stream::UnbufferedStreamBuf;

#include <istream>

NET_NAMESPACE_BEGIN

class CFTPStreamBuf : public UnbufferedStreamBuf
{
public:
	CFTPStreamBuf(std::istream& istr) : m_istr(istr)
	{
		m_istr.exceptions(std::ios::badbit);
	}

	~CFTPStreamBuf()
	{
	}

private:
	int readFromDevice()
	{
		return m_istr.get();
	}

	std::istream& m_istr;
};


class CFTPIOS : public virtual std::ios
{
public:
	CFTPIOS(std::istream& istr) : m_buf(istr)
	{
	  
	}

	~CFTPIOS()
	{
	}

	CFTPStreamBuf* rdbuf()
	{
		return &m_buf;
	}

protected:
	CFTPStreamBuf m_buf;
};


class CFTPStream : public CFTPIOS, public std::istream
{
public:
	CFTPStream(std::istream& istr, CFTPClientSession* pSession)
		: CFTPIOS(istr),
		std::istream(&m_buf),
		m_pSession(pSession)
	{
	}

	~CFTPStream()
	{
		delete m_pSession;
	}

private:
	CFTPClientSession* m_pSession;
};



CFTPPasswordProvider::CFTPPasswordProvider()
{
}

CFTPPasswordProvider::~CFTPPasswordProvider()
{
}


std::string          CFTPStreamFactory::m_anonymousPassword("jhcpp@localhost");
CFTPPasswordProvider* CFTPStreamFactory::m_pPasswordProvider(0);

CFTPStreamFactory::CFTPStreamFactory()
{
}

CFTPStreamFactory::~CFTPStreamFactory()
{
}

std::istream* CFTPStreamFactory::open(const CURI& uri)
{
	jh_assert (uri.getScheme() == "ftp");

	CFTPClientSession* pSession = new CFTPClientSession(uri.getHost(), uri.getPort());
	try
	{
		std::string username;
		std::string password;
		getUserInfo(uri, username, password);

		std::string path;
		char        type;
		getPathAndType(uri, path, type);

		pSession->login(username, password);
		if (type == 'a')
			pSession->setFileType(CFTPClientSession::TYPE_TEXT);

		CPath p(path, CPath::PATH_LUNIX);
		p.makeFile();
		for (int i = 0; i < p.depth(); ++i)
			pSession->setWorkingDirectory(p[i]);
		std::string file(p.getFileName());
		std::istream& istr = (type == 'd' ? pSession->beginList(file) : pSession->beginDownload(file));
		return new CFTPStream(istr, pSession);
	}
	catch (...)
	{
		delete pSession;
		throw;
	}
}

void CFTPStreamFactory::setAnonymousPassword(const std::string& password)
{
	m_anonymousPassword = password;
}

const std::string& CFTPStreamFactory::getAnonymousPassword()
{
	return m_anonymousPassword;
}

void CFTPStreamFactory::setPasswordProvider(CFTPPasswordProvider* pProvider)
{
	m_pPasswordProvider = pProvider;
}

CFTPPasswordProvider* CFTPStreamFactory::getPasswordProvider()
{
	return m_pPasswordProvider;
}

void CFTPStreamFactory::splitUserInfo(const std::string& userInfo, std::string& username, std::string& password)
{
	std::string::size_type pos = userInfo.find(':');
	if (pos != std::string::npos)
	{
		username.assign(userInfo, 0, pos++);
		password.assign(userInfo, pos, userInfo.size() - pos);
	}
	else username = userInfo;
}

void CFTPStreamFactory::getUserInfo(const CURI& uri, std::string& username, std::string& password)
{
	splitUserInfo(uri.getUserInfo(), username, password);
	if (username.empty())
	{
		username = "anonymous";
		password = m_anonymousPassword;
	}
	else if (password.empty())
	{
		if (m_pPasswordProvider)
			password = m_pPasswordProvider->password(username, uri.getHost());
		else
			throw FTPException(std::string("Password required for ") + username + "@" + uri.getHost());
	}
}

void CFTPStreamFactory::getPathAndType(const CURI& uri, std::string& path, char& type)
{
	path = uri.getPath();
	type = 'i';
	std::string::size_type pos = path.rfind(';');
	if (pos != std::string::npos)
	{
		if (path.length() == pos + 7 && path.compare(pos + 1, 5, "type=") == 0)
		{
			type = path[pos + 6];
			path.resize(pos);
		}
	}
}

void CFTPStreamFactory::registerFactory()
{
	CURIStreamOpener::defaultOpener().registerStreamFactory("ftp", new CFTPStreamFactory);
}

void CFTPStreamFactory::unregisterFactory()
{
	CURIStreamOpener::defaultOpener().unregisterStreamFactory("ftp");
}


NET_NAMESPACE_END
